package com.pet.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Data
@Component
public class AliOSSUtils {
    // 读取配置文件
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 上传图片到 阿里云OSS
     * @param tag 图片标签
     * @param file 图片文件
     * @return
     * @throws IOException
     */
    public String upload(String tag, MultipartFile file) throws IOException{
        // 1. 获取上传文件的输入流
        InputStream inputStream = file.getInputStream();
        // 设置图片名
        String oldFileName = file.getOriginalFilename();
        assert oldFileName != null;

        // 时间戳+UUID前5位+图片名为原始文件名[限制为10]
        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 5) + "_"
                + oldFileName.substring(0, Math.min(oldFileName.length(), 10));

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, tag+"/" + fileName, inputStream);
        // 上传字符串。
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        String url = endpoint.split("//")[0] + "//" + bucketName + "."+ endpoint.split("//")[1] + "/" + tag + "/" + fileName;
        ossClient.shutdown();
        return url;
    }

    /**
     * 判断文件是否存在
     * @param url 图片地址
     * @return 若存在则返回true
     */
    public boolean isExistedOSSFile(String url){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String[] split = url.split("/");
        // 最后一个是图片名称，倒数第二个是标签名称
        if(split.length < 2) return false;
        String checkUrl = split[split.length - 2] +
                "/" +
                split[split.length - 1];
        return ossClient.doesObjectExist(bucketName, checkUrl);
    }
}
